#coding=utf-8
import requests;
from requests import exceptions;

import json;

from requests import Request,Session;
#https://httpbin.org


# 设置请求头信息，获取请求头信息
def request_header():
    headers = {"Content-Type": "application/json; charset=utf-8"};
    #设置请求头信息
    response = requests.get("http://www.miaoe.com", headers=headers);
    #设置响应编码
    response.encoding = "utf-8";
    #type() 查看数据类型
    print(dir(response.request.headers))
    print(response.request.headers.items())

# 设置超时时间
def timeout_request():
    url = "http://www.miaoe.com";
    try:
        response = requests.get(url,timeout=2.5);
        # 如果不是200抛出异常
        response.raise_for_status();
    except exceptions.Timeout as e:
        print("超时：",e)
    else:
        print("正常：",response.text)

# 对比 response中的text,content的差别
# text 为str类型
# content 为bytes类型
def response_text_content():
    url = "http://www.miaoe.com";
    response = requests.get(url);

    print(type(response.content))
    print(type(response.text))

    print(type(response.prepare().body))


#使用Request 对象
def hard_requests():
    from requests import Request, Session
    s = Session()
    headers = {'User-Agent': 'fake1.3.4',"Authorization":"Basic aW1vb2NkZW1vOmltb29jZGVtbw=="}
    url = 'https://api.github.com/users/zsjdxc251'
    #request = Request('GET',url,auth=('imoocdemo','imoocdemo'),headers=headers)
    #print(type(request))
    request = Request('GET', url,data="{'a':'b'}")
    prepped = request.prepare()
    print(prepped.body)
    print(prepped.headers)
    response = s.send(prepped, timeout=5)
    print(response.status_code);

# 设置请求参数 data  注意：   data='{"d":b}' 中必须是单引号包含双引号，因为在java JSON格式化是指人双引号
def request_params():
    session = Session();
    url = "http://localhost:8080/gril/update";

    request = Request('POST', url, data='{"a":"b"}',headers={"Content-Type":"application/json; charset=utf-8"})
    prepped = request.prepare()
    print(prepped.body)
    response = session.send(prepped, timeout=5);
    print(response.text)
    pass;


def request_hooks_callback(response, *args, **kwargs):
    print(response.headers['Content-Type'])
    print(args)
    print(kwargs)
    pass;

# 设置请求钩子
def request_hooks():
    response = requests.get("https://api.github.com", hooks=dict(response=request_hooks_callback))

    print(response.text);
    print(response.headers["Content-Type"]);
    pass;

request_hooks();
# json对象转字符串
#json.dump()
#字符串转json对象
#print(json.loads('{"parrot": 42, "spam": "foo","list":["1","2"]}'))
